package scc.project.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import scc.project.dao.GoodsDao;
import scc.project.dao.SellInfoDao;
import scc.project.entity.Goods;
import scc.project.entity.SellInfo;
import scc.project.entity.SellInfoGoods;
import scc.project.entity.pojo.SellInfoPojo;
import scc.project.entity.vo.SellInfoVo;
import scc.project.entity.vo.PageVo;

import java.util.List;

/**
 * 销售的业务类
 *
 * @author 陈圳佳
 */
@Service
public class SellInfoService {

    @Autowired
    private SellInfoDao sellInfoDao;
    @Autowired
    private GoodsDao goodsDao;

    /**
     * 添加销售单
     */
    public boolean save(SellInfoVo sellInfo) {
        Double totalPrice = 0d;
        for (SellInfoGoods infoGoods : sellInfo.getInfoGoods()) {
            Goods goods = goodsDao.selectById(infoGoods.getGoodsId());
            Integer number = goods.getNumber();
            if (number < infoGoods.getTotal())
                throw new RuntimeException("貌似库存不够了");
            goodsDao.updateNumberById(infoGoods.getTotal(), infoGoods.getGoodsId());
            totalPrice += infoGoods.getTotalPrice();
        }
        String code = sellInfoDao.selectSellInfoCode(sellInfo.getSellDate());
        sellInfo.setCode(code);
        sellInfo.setTotalPrice(totalPrice);
        int b = sellInfoDao.insert(sellInfo);
        if (b <= 0)
            throw new RuntimeException("添加失败了!");
        for (SellInfoGoods infoGoods : sellInfo.getInfoGoods()) {
            int count = sellInfoDao.insertForeign(sellInfo.getId(), infoGoods.getGoodsId(), infoGoods.getTotal());
            if (count <= 0) {
                throw new RuntimeException("出错了");
            }
        }
//      销售成功后修改库存
        return true;
    }

    public PageVo<SellInfo> find(Integer page, String emp, String custom) {
        PageVo<SellInfo> pageVo = new PageVo<SellInfo>(page);
        List<SellInfo> sellInfoVos = sellInfoDao.find(pageVo.getRows(), pageVo.getOffset(), emp, custom);
        pageVo.setData(sellInfoVos);
        Long total = sellInfoDao.findTotal(emp, custom);
        pageVo.setTotal(total);
        return pageVo;
    }

    public SellInfoPojo get(Long id) {
        return sellInfoDao.selectById(id);
    }
}
